package red.sms.db.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import red.sms.db.config.DBConfig;
import red.sms.db.config.ServiceConfig;
import red.sms.db.entity.SmsMO;
import red.sms.util.Logger;
public class SmsMoDAO {
	public static DBConfig dbc = new DBConfig();
	
		public static SmsMO dequeue(String commandCode, String maDichVu) {
		     try {
			       Connection con = ConnectionFactory.getInstance().getConnection();
				   Statement stmt = con.createStatement();
				   ResultSet result = stmt.executeQuery("SELECT * FROM sms_mo where active_flag = 1 ORDER BY update_date DESC LIMIT 1");
				   SmsMO smsMo = new SmsMO();
			          while(result.next())
			          {  
			             smsMo.setMoId(result.getInt("mo_id"));
			             smsMo.setRequestId(result.getString("request_id"));
			             smsMo.setInfo(result.getString("info"));
			             smsMo.setMaDichVu(result.getString("ma_dich_vu"));
			             smsMo.setPhoneNumber(result.getString("phone_number"));
			             smsMo.setCommandCode(result.getString("command_code"));
			          }
			          
			          if ((smsMo.getRequestId() != null) && (ServiceConfig.checkCommandCode(commandCode)) && (ServiceConfig.checkMaDichVu(maDichVu))){
			    	   String updateSql = "UPDATE  sms_mo SET active_flag = 0 WHERE request_id = " + smsMo.getRequestId();
			    	   PreparedStatement ps = con.prepareStatement(updateSql);
			    	   ps.executeUpdate();
			       }
			           
			          con.close();
			          return smsMo;
		      } catch (Exception ex) {
		    	  ex.printStackTrace();
		    	  Logger.log("\n"+ ex.getMessage(), true);
		    	  return null;
		      }
		  }
	
	public static void updateQueue(String request_id) {
	      try {
	    	  String updateSql = "UPDATE  sms_mo SET active_flag = 0 WHERE request_id = " + request_id;
	          Class.forName("com.mysql.jdbc.Driver");
	          Connection con = ConnectionFactory.getInstance().getConnection();
	          PreparedStatement ps = con.prepareStatement(updateSql);
	          ps.executeUpdate();
	          con.close();
	      } catch (Exception ex) {
	    	  Logger.log("\n"+ ex.getMessage(), true);
	      }
	  }
}

